package com.liao.mvc.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liao.mvc.dao.CriteriaCustomer;
import com.liao.mvc.dao.CustomerDAO;
import com.liao.mvc.dao.impl.CustomerDAOJdbcImpl;
import com.liao.mvc.domain.Customer;

/**
 * Servlet implementation class CustomerServlet
 */
public class CustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private CustomerDAO customerDAO = new CustomerDAOJdbcImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	/*
	 * protected void doPost(HttpServletRequest request, HttpServletResponse
	 * response) throws ServletException, IOException { // TODO Auto-generated
	 * method stub String method = request.getParameter("method"); switch
	 * (method) { case "add": add (request,response); break; case "query": query
	 * (request,response); break; case "delete": delete(request, response);
	 * break; } }
	 */

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.获取ServletPath: /query.do或
		String servletPath = request.getServletPath();
		// 2.去除/ 和 .do ，得到类似于query或 这样的字符串
		String methodName = servletPath.substring(1);
		methodName = methodName.substring(0, methodName.length() - 3);
		Method method;
		try {
			// 3. 利用反射获取methodName 对应的方法
			method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			// 4. 利用反射调用对应的方法
			method.invoke(this, request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block

			// 5. 出错时响应
			response.sendRedirect("error.jsp");
		}

	}

	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String forwardPath = "/error.jsp";
		// 1. 获取请求参数 id
		String idStr = request.getParameter("id");
		System.out.println(idStr);
		// 2. 调用CustomerDAO 的customerDAO.get(id）获取和id对应的Customer对象customer

		try {
			Customer customer = customerDAO.get(Integer.parseInt(idStr));
			if (customer != null) {
				forwardPath = "/updatecustomer.jsp";
				// 3. 将customer放入request中
				request.setAttribute("customer", customer);
			}
		} catch (NumberFormatException e) {
		}

		// 4. 响应updatecustomer.jsp 页面：转发
		request.getRequestDispatcher(forwardPath).forward(request, response);

	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("update");

		// 1. 获取表单参数 id,name,address,phone,oldname
		String id = request.getParameter("id");
		String oldname = request.getParameter("oldname");
		String name = request.getParameter("name");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		
		// 2. 检验 name 是否重复
		// 2.1 比较name和oldname是否相同，若相同说明name可用
		// 2.2 若不相同，则调用CustomerDAO 的getCountWithName(String name)
		// 获取name在数据库中是否存在
		
	
		if (!oldname.equalsIgnoreCase(name)) {
			long count = customerDAO.getCountWithName(name);
			// 2.3若返回值大于0，则响应updatecustomer.jsp页面：通过转发的方式来响应newcustomer.jsp
			if (count > 0) {
				// 2.3.1 在updatecustomer.jsp页面显示一个错误消息：用户名已经被占用
				// 在request中放入一个属性message：用户名已经被占用
				// 在页面上通过request.getAttribute("message")的方式来显示
				request.setAttribute("message", "用户名" + name + "已被占用");
				// 2.3.2 newcustomer.jsp的表单值可以回显
				// address,phone显示提交表单的新值，而name显示oldname
				// 通过value="<%=request.getParameter("name") == null ? "" :
				// request.getParameter("name") %>" 来进行回显
				// 2.3.3 结束方法：return
				request.getRequestDispatcher("/updatecustomer.jsp").forward(request, response);
				return;
			}
		}  

		// 3. 若验证通过，则把表单参数封装为一个Customer 对象 customer
		Customer customer = new Customer(name,address,phone);
		customer.setId(Integer.parseInt(id));
		System.out.println(customer);
		// 4. 调用CustomerDAO的save(Customer customer) ，执行保存操作
		customerDAO.update(customer);
		// 5. 重定向到query.do
		response.sendRedirect("query.do");

	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String idStr = request.getParameter("id");
		System.out.println(idStr);
		int id = 0;
		// try....catch的作用：防止idStr 不能转为 int类型
		// 若不能转 则id=0,无法进行任何的删除操作
		try {
			id = Integer.parseInt(idStr);
			customerDAO.delete(id);

		} catch (Exception e) {
			// TODO: handle exception
		}
		response.sendRedirect("query.do");
	}

	private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取模糊查询的请求参数

		String name = request.getParameter("name");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		CriteriaCustomer cc = new CriteriaCustomer(name, address, phone);

		// 1. 调用CustomerDAO 的 getAll()方法， 得到Customer 的集合
		// List<Customer>customers= customerDAO.getAll();
		List<Customer> customers = customerDAO.getForListWithCriteriaCustomer(cc);

		// 2. 把Customer的集合放入 request 中
		request.setAttribute("customers", customers);
		// 3. 转发页面到index.jsp（不能使用重定向）
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	private void addCustomer(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1. 获取表单参数 ：name,address,phone
		String name = request.getParameter("name");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		// 2. 检验 name 是否重复
		// 2.1 调用CustomerDAO 的getCountWithName(String name) 获取name在数据库中是否存在
		long count = customerDAO.getCountWithName(name);
		// 2.2 若返回值大于0，则响应newcustomer.jsp页面：
		// 通过转发的方式来响应newcustomer.jsp
		if (count > 0) {
			// 2.2.1 要求在nwecustomer.jsp页面显示一个错误信息：用户名name 已经被占用
			// 在request 中放入一个属性message：用户名
			// name已经被占用。在页面上通过request.getAttribute("message")的方式来显示
			request.setAttribute("message", "用户名" + name + "已经被占用");
			// 2.2.2 newcustomer.jsp的表单值可以回显
			// 通过value="<%=request.getParameter("name") == null ? "" :
			// request.getParameter("name") %>" 来进行回显
			// 2.2.3 结束方法：return
			request.getRequestDispatcher("/newcustomer.jsp").forward(request, response);
			return;
		}
		// 3. 若验证通过，则把表单参数封装为一个Customer 对象 customer
		Customer customer = new Customer(name, address, phone);
		// 4. 调用CustomerDAO的save(Customer customer) ，执行保存操作
		customerDAO.save(customer);
		// 5. 重定向到success.jsp 页面
		response.sendRedirect("success.jsp");
	}

}
